package com.hemaapp.yjnh.activity;

import de.greenrobot.event.EventBus;
import xtom.frame.XtomConfig;
import xtom.frame.image.cache.XtomImageCache;
import xtom.frame.media.XtomVoicePlayer;
import xtom.frame.util.XtomBaseUtil;
import xtom.frame.util.XtomSharedPreferencesUtil;
import xtom.frame.util.XtomToastUtil;
import android.app.ActionBar.LayoutParams;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;

import com.hemaapp.yjnh.db.UserDBHelper;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.SysInitInfo;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.HemaUtil;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog.OnButtonListener;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseApplication;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.BaseUpGrade;
import com.hemaapp.yjnh.BaseUtil;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.view.ShareDialog;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.media.UMImage;

import java.io.File;
import java.util.Arrays;

public class SettingActivity extends BaseActivity implements OnClickListener {

	private ImageButton left;
	private TextView title;
	private Button titleRight;

	private LinearLayout loginPwdLayout;
	private LinearLayout tixianPwdLayout;
	private CheckBox wifi;
	private LinearLayout ll_check_update;
	private TextView version;
	private LinearLayout ll_feedback;
	private LinearLayout ll_aboutus;
	private LinearLayout ll_clear_cache;
	private TextView tv_cache;
	private LinearLayout ll_call_server;
	private LinearLayout ll_score;
	private LinearLayout ll_share;
	private Button btn_logout;

	private SysInitInfo sysInitInfo;
	PopupWindow pop;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_setting);
		super.onCreate(savedInstanceState);
		String sysVersion = getApplicationContext().getSysInitInfo()
				.getSys_last_version();
		String version = HemaUtil.getAppVersionForSever(mContext);
		try {
			this.version.setText("当前版本："+XtomBaseUtil.getAppVersionName(mContext));
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		if (HemaUtil.isNeedUpDate(version, sysVersion)) {
			this.version.setText("有新版本："+sysVersion);
		}
        getDiskCacheSize(mContext, tv_cache);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.login_pwd_lay:
			if (BaseUtil.isLogin()) {
				Intent itMod = new Intent(mContext, PwdresetActivity.class);
				itMod.putExtra("type", 1);
				startActivity(itMod);
			} else {
				BaseUtil.checkLogin(mContext);
			}
			break;
		case R.id.tixian_pwd_lay:
			if (BaseUtil.isLogin()) {
				Intent itMod = new Intent(mContext, PwdresetActivity.class);
				itMod.putExtra("type", 2);
				startActivity(itMod);
			} else {
				BaseUtil.checkLogin(mContext);
			}
			break;
		case R.id.title_left_btn:
			finish();
			break;
		case R.id.ll_share:
			String content = getApplicationContext().getSysInitInfo().getMsg_invite();
			//分享链接和图片链接
            String imgUrl = "";
			String sys_plugins = getApplicationContext().getSysInitInfo().getSys_plugins();
			String path = sys_plugins + "share/sdk.php?id=0";
			User user = getApplicationContext().getUser();
			if (user != null) {
				imgUrl = user.getCodeurl();
				path = "http://123.57.210.14/index.php/user/register.html?username="+user.getUsername();//如果已经登录就
			}
			//图片url
			UMImage image = null;
			if (!isNull(imgUrl)) {
				image = new UMImage(mContext, imgUrl);
			}else {
				imgUrl = BaseUtil.getLogoImagePath(mContext);
                image = new UMImage(mContext, BitmapFactory.decodeFile(imgUrl));
			}
			new ShareDialog(SettingActivity.this, "大家一起注册易家农户" , content, path, image)
					.builder().show();
			break;
		case R.id.ll_check_update:
			getNetWorker().init();
			break;
		case R.id.ll_feedback:
			if (BaseUtil.isLogin()) {
				Intent itFeedback = new Intent(mContext, FeedbackActivity.class);
				startActivity(itFeedback);
			} else {
				BaseUtil.checkLogin(mContext);
			}
			break;
		case R.id.ll_aboutus:
			Intent itAbout = new Intent(mContext, WebviewActivity.class);
			itAbout.putExtra("parm", "aboutus");
			itAbout.putExtra("type", 3);
			startActivity(itAbout);
			break;
		case R.id.ll_clear_cache:
			new ClearTask().execute();
            clearImageDiskCache();
            clearImageMemoryCache();
			break;
		case R.id.ll_score:
			try {
				Uri uri = Uri.parse("market://details?id=" + getPackageName());
				Intent intent = new Intent(Intent.ACTION_VIEW, uri);
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(intent);
			}catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case R.id.btn_logout:
			if (getApplicationContext().getUser() == null) {
				BaseUtil.checkLogin(mContext);
				break;
			}
			HemaButtonDialog lodialog = new HemaButtonDialog(mContext);
			lodialog.setText("确定要退出当前账户？");
			lodialog.setRightButtonText("确定");
			lodialog.setRightButtonTextColor(getResources().getColor(R.color.theme_orange));
			lodialog.setLeftButtonText("取消");
			lodialog.setButtonListener(new OnButtonListener() {

				@Override
				public void onRightButtonClick(HemaButtonDialog dialog) {
					getNetWorker().clientLoginout(
							getApplicationContext().getUser().getToken());
					dialog.cancel();
				}

				@Override
				public void onLeftButtonClick(HemaButtonDialog dialog) {
					dialog.cancel();
				}
			});
			break;
		case R.id.ll_call_server:
			HemaButtonDialog hbdialog = new HemaButtonDialog(mContext);
			hbdialog.setText(getApplicationContext().getSysInitInfo()
					.getSys_service_phone());
			hbdialog.setRightButtonText("拨打");
			hbdialog.setLeftButtonText("取消");
			hbdialog.setRightButtonTextColor(getResources().getColor(R.color.theme_orange));
			hbdialog.setButtonListener(buttonListener);
			break;
		default:
			break;
		}
	}

	private OnButtonListener buttonListener = new HemaButtonDialog.OnButtonListener() {

		@Override
		public void onRightButtonClick(HemaButtonDialog dialog) {
			dialog.cancel();
			Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"
					+ getApplicationContext().getSysInitInfo()
							.getSys_service_phone()));
			startActivity(intent);
		}

		@Override
		public void onLeftButtonClick(HemaButtonDialog dialog) {
			dialog.cancel();
		}
	};

	private class ClearTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			// 删除图片缓存
			XtomImageCache.getInstance(mContext).deleteCache();
			// 删除语音缓存
			XtomVoicePlayer player = XtomVoicePlayer.getInstance(mContext);
			player.deleteCache();
			player.release();
			return null;
		}

		@Override
		protected void onPreExecute() {
			showProgressDialog("正在清除缓存");
		}

		@Override
		protected void onPostExecute(Void result) {
			cancelProgressDialog();
			// showTextDialog("清除完成");
			new Handler().postDelayed(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					showPop();
					// pop.dismiss();
				}
			}, 500);
		}
	}

	private void showPop() {
		// TODO Auto-generated method stub
		View view = getLayoutInflater().inflate(R.layout.pop_cache_success,
				null);
		pop = new PopupWindow(view, LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);
		pop.setOutsideTouchable(true);
		pop.setFocusable(true);
		pop.setBackgroundDrawable(new BitmapDrawable());
		pop.showAsDropDown(findViewById(R.id.ll_item));
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				pop.dismiss();
			}
		}, 1000);
	}

	@Override
	protected void callBeforeDataBack(HemaNetTask netTask) {
		BaseHttpInformation info = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (info) {
		case CLIENT_LOGINOUT:
			showProgressDialog("正在注销");
			break;

		default:
			break;
		}
	}

	@Override
	protected void callAfterDataBack(HemaNetTask netTask) {
		BaseHttpInformation info = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (info) {
		case CLIENT_LOGINOUT:
			cancelProgressDialog();
			break;

		default:
			break;
		}
	}

	@Override
	protected void callBackForServerSuccess(HemaNetTask netTask,
			HemaBaseResult baseResult) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case INIT:
			@SuppressWarnings("unchecked")
			HemaArrayResult<SysInitInfo> sResult = (HemaArrayResult<SysInitInfo>) baseResult;
			sysInitInfo = sResult.getObjects().get(0);
			String sysVersion = sysInitInfo.getSys_last_version();
			String version = HemaUtil.getAppVersionForSever(mContext);
			if (HemaUtil.isNeedUpDate(version, sysVersion)) {
				showUpdateDialog();
			} else {
				showTextDialog("当前已经是最新版本了哦！");
			}
			break;
		case CLIENT_LOGINOUT:
            XtomToastUtil.showShortToast(this, "注销成功");
			XtomSharedPreferencesUtil.save(mContext, "username", "");
			XtomSharedPreferencesUtil.save(mContext, "password", "");
			//清除保存的联系人和手机号
			XtomSharedPreferencesUtil.save(mContext, "bespeak_name", "");
			XtomSharedPreferencesUtil.save(mContext, "bespeak_mobile", "");
            UserDBHelper dbHelper = new UserDBHelper(mContext);
            dbHelper.clear();
            BaseApplication.getInstance().setUser(null);
            EventBusMsg msg = new EventBusMsg();
            msg.setType(EventBusConfig.USER);
            msg.setUser(null);
            EventBus.getDefault().post(msg);
			new Handler().postDelayed(new Runnable() {

				@Override
				public void run() {
					// FyUtil.exit(mContext);
					finish();
				}
			}, 500);
			break;
		default:
			break;
		}
	}

	private HemaButtonDialog updateDialog;

	public void showUpdateDialog() {
		if (updateDialog == null) {
			updateDialog = new HemaButtonDialog(mContext);
			updateDialog.setText("有新的软件版本\n是否升级？");
			updateDialog.setLeftButtonText("取消");
			updateDialog.setRightButtonText("升级");
			updateDialog.setButtonListener(new ButtonListener());
		}
		updateDialog.show();
	}

	private class ButtonListener implements OnButtonListener {
		private BaseUpGrade upGrade;

		@Override
		public void onLeftButtonClick(HemaButtonDialog dialog) {
			dialog.cancel();
		}

		@Override
		public void onRightButtonClick(HemaButtonDialog dialog) {
			dialog.cancel();
			if (upGrade == null)
				upGrade = new BaseUpGrade(mContext);
			upGrade.upGrade(sysInitInfo);
		}
	}

	@Override
	protected void callBackForServerFailed(HemaNetTask netTask,
			HemaBaseResult baseResult) {
		// TODO Auto-generated method stub
		BaseHttpInformation info = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (info) {
		case CLIENT_LOGINOUT:
			showTextDialog(baseResult.getMsg());
			break;
		default:
			break;
		}
	}

	@Override
	protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
		// TODO Auto-generated method stub
		BaseHttpInformation info = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (info) {
		case CLIENT_LOGINOUT:
			showTextDialog("注销失败");
			break;

		default:
			break;
		}
	}

	@Override
	protected void findView() {
		left = (ImageButton) findViewById(R.id.title_left_btn);
		title = (TextView) findViewById(R.id.title_text);
		titleRight = (Button) findViewById(R.id.title_right_btn);
		
		loginPwdLayout = (LinearLayout) findViewById(R.id.login_pwd_lay);
		tixianPwdLayout = (LinearLayout) findViewById(R.id.tixian_pwd_lay);
		wifi = (CheckBox) findViewById(R.id.wifi);
		ll_check_update = (LinearLayout) findViewById(R.id.ll_check_update);
		version = (TextView) findViewById(R.id.version);
		ll_feedback = (LinearLayout) findViewById(R.id.ll_feedback);
		ll_aboutus = (LinearLayout) findViewById(R.id.ll_aboutus);
		ll_clear_cache = (LinearLayout) findViewById(R.id.ll_clear_cache);
        tv_cache = (TextView) findViewById(R.id.tv_cache);
		ll_call_server = (LinearLayout) findViewById(R.id.ll_call_server);
		ll_score = (LinearLayout) findViewById(R.id.ll_score);
		ll_share=(LinearLayout) findViewById(R.id.ll_share);
		btn_logout = (Button) findViewById(R.id.btn_logout);
	}

	@Override
	protected void getExras() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		if (!BaseUtil.isLogin()) {
			btn_logout.setVisibility(View.GONE);
		} else {
			btn_logout.setVisibility(View.VISIBLE);
		}
		super.onResume();
	}

	@Override
	protected void setListener() {
		// TODO Auto-generated method stub
		left.setOnClickListener(this);
		title.setText("设置");
		titleRight.setVisibility(View.GONE);
		
		loginPwdLayout.setOnClickListener(this);
		tixianPwdLayout.setOnClickListener(this);
		ll_check_update.setOnClickListener(this);
		ll_feedback.setOnClickListener(this);
		ll_aboutus.setOnClickListener(this);
		ll_clear_cache.setOnClickListener(this);
		ll_call_server.setOnClickListener(this);
		ll_score.setOnClickListener(this);
		ll_share.setOnClickListener(this);
		btn_logout.setOnClickListener(this);

		String htxz = XtomSharedPreferencesUtil.get(mContext,
				"imageload_onlywifi");
		wifi.setChecked("true".equals(htxz));
		wifi.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (isChecked) {
					XtomConfig.IMAGELOAD_ONLYWIFI = true;
					XtomSharedPreferencesUtil.save(mContext,
							"imageload_onlywifi", "true");
				} else {
					XtomConfig.IMAGELOAD_ONLYWIFI = false;
					XtomSharedPreferencesUtil.save(mContext,
							"imageload_onlywifi", "false");
				}
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		UMShareAPI.get( this ).onActivityResult( requestCode, resultCode, data);
	}

    //计算Glide图片缓存大小
    public void getDiskCacheSize(Context context, TextView textView){
        //获取data下
//        new GetDiskCacheSizeTask(textView).execute(new File(context.getCacheDir(), DiskCache.Factory.DEFAULT_DISK_CACHE_DIR));
        //获取sd卡下
        //new GetDiskCacheSizeTask(textView).execute(new File(context.getExternalCacheDir(),DiskCache.Factory.DEFAULT_DISK_CACHE_DIR));
    }


    class GetDiskCacheSizeTask extends AsyncTask<File, Long, Long>{
        private final TextView resultView;

        public GetDiskCacheSizeTask(TextView resultView) {
            this.resultView = resultView;
        }

        @Override
        protected void onPreExecute() {
            resultView.setText("Calculating...");
        }

        @Override
        protected void onProgressUpdate(Long... values) { /* onPostExecute(values[values.length - 1]); */ }

        @Override
        protected Long doInBackground(File... dirs) {
            try {
                long totalSize = 0;
                for (File dir : dirs) {
                    publishProgress(totalSize);
                    totalSize += calculateSize(dir);
                }
                return totalSize;
            } catch (RuntimeException ex) {
                final String message = String.format("Cannot get size of %s: %s", Arrays.toString(dirs), ex);
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        resultView.setText("error");
                        Toast.makeText(resultView.getContext(),message, Toast.LENGTH_LONG).show();
                    }
                });
            }
            return 0L;
        }

        @Override
        protected void onPostExecute(Long size) {
            String sizeText = android.text.format.Formatter.formatFileSize(resultView.getContext(), size);
            resultView.setText(sizeText);
        }

        private long calculateSize(File dir) {
            if (dir == null) return 0;
            if (!dir.isDirectory()) return dir.length();
            long result = 0;
            File[] children = dir.listFiles();
            if (children != null)
                for (File child : children)
                    result += calculateSize(child);
            return result;
        }
    }

	/** * 清除图片磁盘缓存 */
	public void clearImageDiskCache() {
//		try {
//			if (Looper.myLooper() == Looper.getMainLooper()) {
//				//只能在非主线程执行
//				new Thread(new Runnable() {
//					@Override public void run() {
//						Glide.get(mContext).clearDiskCache();
//					}
//				});
//			} else {
//				Glide.get(mContext).clearDiskCache();
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
		ImageLoader.getInstance().clearDiskCache();
	}

	/** * 清除图片内存缓存 */
	public void clearImageMemoryCache() {
//		try {
//			Glide.get(mContext).clearMemory();
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
		ImageLoader.getInstance().clearMemoryCache();  // 清除内存缓存
	}

}
